{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer=size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                for n in range(num_layers):\n",
    "                    (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                        cell_fw = cells(size_layer // 2),\n",
    "                        cell_bw = cells(size_layer // 2),\n",
    "                        inputs = encoder_embedded,\n",
    "                        sequence_length = self.X_seq_len,\n",
    "                        dtype = tf.float32,\n",
    "                        scope = 'bidirectional_rnn_%d'%(n))\n",
    "                    encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "                    \n",
    "                bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "                last_state = tuple([bi_state] * num_layers)\n",
    "                last_output = tf.concat((out_fw,out_bw), -1)\n",
    "\n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-12ce5bc9babe>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-12ce5bc9babe>:36: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-12ce5bc9babe>:48: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-12ce5bc9babe>:58: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 20652, 20652, 10810,  5540,  5355,  5355, 31771, 31771,\n",
       "          29764, 27073, 27073, 27073, 11704, 11704, 11704, 11704, 22388,\n",
       "          22388, 22388,  8874,  8874,  8874,  1856, 27233, 27233, 27233,\n",
       "          27233, 31395, 22128, 22128, 22128,  1055,  1055,  1055,  1055,\n",
       "           3039]],\n",
       " \n",
       "        [[    1, 12246, 12246, 12246, 24651, 11029,  1100, 29880, 27075,\n",
       "          29880, 13243, 12246,  6685,  6685,  6685,  6437,  6437,  6437,\n",
       "           5052,  5052, 23369, 23369, 29648, 29435, 29435, 10550, 10550,\n",
       "          13703, 10631, 10631, 10631, 10631, 10631,  1103,  9563,  9563,\n",
       "           9563]],\n",
       " \n",
       "        [[    1,  3183, 15312,  3759, 22196, 19342, 19342, 19342, 28582,\n",
       "          28582,  9340,  9340,  7594,  7594, 14267, 14267,   721, 19772,\n",
       "          19772,  9263,  9263, 23839, 23839, 23839,  9263,  2969,  2969,\n",
       "           2969, 22764,  9263, 22764,  9263, 27219, 27219, 27219, 27219,\n",
       "          27219]],\n",
       " \n",
       "        [[    1, 31561, 31561, 31561, 15722,   612,   612, 27056, 28462,\n",
       "          28462,  4865,   370,  3522,  7286,  9094,  9094, 22778, 22778,\n",
       "          10574, 10574, 10574, 10574, 11005, 11005, 19382, 19382, 19382,\n",
       "          23642, 30970, 30970, 30970, 30970,  9190,  6149,  9190,  9190,\n",
       "           9190]],\n",
       " \n",
       "        [[    1,  9311, 24914, 24914, 15999, 15999, 31762, 31762, 31750,\n",
       "          16957, 25963, 13733, 13733, 28114,  4601, 18975, 18975, 18975,\n",
       "           3487,  3487, 21915, 21915,  6860,  6860, 19533, 12601, 12601,\n",
       "          17425, 17425, 17425,  4052,  4052,  4052, 11497, 11497, 15841,\n",
       "          15841]],\n",
       " \n",
       "        [[    1, 23145, 23145, 15066, 27457, 31561, 31561,  9909, 14178,\n",
       "          14178, 29732, 29732, 14579, 14579, 13734, 13734,  2951,  2158,\n",
       "           9173,  4596,  4596, 12257,  3332,  3332, 29760, 29760, 29760,\n",
       "          14251, 14251,   282,   282, 30878, 30878, 27575, 27575, 11518,\n",
       "          11518]],\n",
       " \n",
       "        [[    1,  6392,  4696, 22583, 22583, 22583,  1479,  1479,  1479,\n",
       "           3233,  3233,  3233,  3233,  3588,  3588,  3607, 23170, 18461,\n",
       "          18461, 19234, 31243, 31243, 24895, 24895,  7804,  6917,  6917,\n",
       "          27315, 27315, 27315, 27315,  5367, 18717,  7025,  7025,  7025,\n",
       "          14113]],\n",
       " \n",
       "        [[    1, 15703, 15703, 20285,  3908,  1838,  1838,  1838,  5975,\n",
       "          19133, 19133, 19133, 10342,  1825,  1825,  1825, 19786, 19786,\n",
       "          19786, 19247, 19247, 19247, 15526,  4611,  4611, 15526, 31130,\n",
       "          31130, 31130, 11182, 11182, 11182, 11182, 11182, 15732,  5364,\n",
       "          31130]],\n",
       " \n",
       "        [[    1, 23070, 23070, 17032, 26381, 26381, 30808, 24581, 24581,\n",
       "          17250, 17250, 17250, 15063, 15063, 17183, 19862, 30162, 30162,\n",
       "          29751, 29353, 29353, 29353, 31743, 31743, 31743, 31743, 31743,\n",
       "          19517, 19517, 21429, 21429, 23037, 23037, 29292, 29292, 28634,\n",
       "          16432]],\n",
       " \n",
       "        [[    1, 19517,  4687, 14218, 14218, 26538, 26233, 26233, 26538,\n",
       "           2671,  2671,  2671, 19753, 19753, 19753, 19753, 16998, 16998,\n",
       "           7716,  7716,  7716,  7716,  7716,  7716, 11052, 11052,  1287,\n",
       "          11052, 10503, 10503, 18788, 18788, 18788, 22247, 22247, 22247,\n",
       "           6424]]], dtype=int32), 10.374498, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:32<00:00,  2.08it/s, accuracy=0.128, cost=6.31]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.58it/s, accuracy=0.14, cost=6.01] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.771327, training avg acc 0.121621\n",
      "epoch 1, testing avg loss 6.224378, testing avg acc 0.138687\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.148, cost=5.38]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.73it/s, accuracy=0.129, cost=5.91]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 5.835042, training avg acc 0.151359\n",
      "epoch 2, testing avg loss 5.844088, testing avg acc 0.152161\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.16, cost=4.98] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.67it/s, accuracy=0.113, cost=5.96]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.383654, training avg acc 0.164599\n",
      "epoch 3, testing avg loss 5.822752, testing avg acc 0.152789\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:06<00:00,  1.99it/s, accuracy=0.17, cost=4.67] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.73it/s, accuracy=0.14, cost=5.76] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.083283, training avg acc 0.175035\n",
      "epoch 4, testing avg loss 5.674973, testing avg acc 0.155929\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.174, cost=4.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.70it/s, accuracy=0.161, cost=5.64]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.862185, training avg acc 0.183493\n",
      "epoch 5, testing avg loss 5.716104, testing avg acc 0.152370\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.214, cost=4.13]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.71it/s, accuracy=0.14, cost=5.76] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.690091, training avg acc 0.191210\n",
      "epoch 6, testing avg loss 5.754491, testing avg acc 0.153232\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.223, cost=4.05]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.71it/s, accuracy=0.134, cost=5.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.561849, training avg acc 0.197910\n",
      "epoch 7, testing avg loss 5.731814, testing avg acc 0.152908\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.21, cost=4.08] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.72it/s, accuracy=0.14, cost=5.82] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.459563, training avg acc 0.204059\n",
      "epoch 8, testing avg loss 5.796527, testing avg acc 0.154424\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.247, cost=3.9] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.70it/s, accuracy=0.129, cost=5.79]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.384163, training avg acc 0.208627\n",
      "epoch 9, testing avg loss 5.816069, testing avg acc 0.154277\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:06<00:00,  1.99it/s, accuracy=0.251, cost=3.75]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.72it/s, accuracy=0.161, cost=5.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.294431, training avg acc 0.215639\n",
      "epoch 10, testing avg loss 5.849307, testing avg acc 0.156239\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.266, cost=3.61]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.65it/s, accuracy=0.161, cost=5.87]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 4.239342, training avg acc 0.219068\n",
      "epoch 11, testing avg loss 5.852525, testing avg acc 0.156102\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:07<00:00,  1.98it/s, accuracy=0.248, cost=3.79]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.71it/s, accuracy=0.161, cost=5.91]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 4.128561, training avg acc 0.229413\n",
      "epoch 12, testing avg loss 5.922250, testing avg acc 0.153639\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.255, cost=3.62]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.72it/s, accuracy=0.167, cost=5.89]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 4.176851, training avg acc 0.222483\n",
      "epoch 13, testing avg loss 5.950550, testing avg acc 0.153538\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:03<00:00,  1.99it/s, accuracy=0.266, cost=3.59]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.70it/s, accuracy=0.156, cost=5.83]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 4.126416, training avg acc 0.227567\n",
      "epoch 14, testing avg loss 5.961139, testing avg acc 0.152671\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:04<00:00,  1.99it/s, accuracy=0.264, cost=3.56]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.70it/s, accuracy=0.118, cost=5.77]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 4.142272, training avg acc 0.225033\n",
      "epoch 15, testing avg loss 5.957283, testing avg acc 0.153810\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:05<00:00,  1.99it/s, accuracy=0.258, cost=3.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.70it/s, accuracy=0.134, cost=5.9] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 4.051170, training avg acc 0.234105\n",
      "epoch 16, testing avg loss 6.101645, testing avg acc 0.150027\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:04<00:00,  1.99it/s, accuracy=0.273, cost=3.55]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.73it/s, accuracy=0.151, cost=5.73]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 4.003989, training avg acc 0.238874\n",
      "epoch 17, testing avg loss 6.030329, testing avg acc 0.152667\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:30<00:00,  2.08it/s, accuracy=0.27, cost=3.55] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.02it/s, accuracy=0.14, cost=6]    \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.944596, training avg acc 0.245413\n",
      "epoch 18, testing avg loss 6.134459, testing avg acc 0.149721\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:24<00:00,  2.10it/s, accuracy=0.282, cost=3.43]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.08it/s, accuracy=0.167, cost=5.87]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 4.035424, training avg acc 0.237180\n",
      "epoch 19, testing avg loss 6.034005, testing avg acc 0.153321\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:20<00:00,  2.11it/s, accuracy=0.298, cost=3.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.134, cost=6.08]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.924935, training avg acc 0.246241\n",
      "epoch 20, testing avg loss 6.116434, testing avg acc 0.151942\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [04:47<00:00,  7.18s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.027758315"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
